﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Omu.Awesome.Core;
using Omu.Awesome.Mvc;
using Omu.AwesomeDemo.Core.Model;
using Omu.AwesomeDemo.Core.Repository;

namespace Omu.AwesomeDemo.WebUI.Controllers
{
    public class PersonaLookupController : LookupController
    {
        private readonly IRepo<Person> repo;

        public PersonaLookupController(IRepo<Person> repo)
        {
            this.repo = repo;
        }

        [HttpPost]
        public ActionResult Search(string search, IEnumerable<int> selected)
        {
            var result =
                repo.GetAll().Where(o => o.FirstName.Containz(search) || o.LastName.Containz(search));

            return View(@"Awesome\LookupList", result.Where(o => selected == null || !selected.Contains(o.Id)).ToList());
        }

        public ActionResult Get(int id)
        {
            var person = repo.Get(id);
            return person == null ? Content("person deleted") : Content(person.FirstName + " " + person.LastName);
        }

        #region needed only if you use multiselect = true
        public ActionResult Selected(IEnumerable<int> selected)
        {
            return View(@"Awesome\LookupList", repo.GetAll().Where(o => selected != null && selected.Contains(o.Id)));
        }

        public ActionResult GetMultiple(IEnumerable<int> selected)
        {
            return Json(repo.GetAll().Where(o => selected.Contains(o.Id)).Select(v => new { Text = v.FirstName + ' ' + v.LastName }));
        }
        #endregion
    }
}